<?php

namespace app\api\command;

use addons\shopro\model\Order;

use app\admin\controller\share\Reward;
use app\admin\model\exchange\Code;
use app\admin\model\share\CommonShare;
use app\admin\model\share\ShareUser;
use app\common\model\RechargeBill;
use app\common\model\Reword;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\model\UserChangeLog;
use think\Db;
use app\common\library\Auth;

class FiveTimer extends Command
{
    protected function configure()
    {
        $this->setName('FiveTimer')->setDescription('five timer');
    }

    protected function execute(Input $input, Output $output)
    {
        //自动销号
        $this->Canceluser($input, $output);
        echo 11 . PHP_EOL;

        //测试号退单
        (new ShareUser())->del_test_user();

        echo 22 . PHP_EOL;
        //分账
        (new CommonShare())->orderBillAdd();
        //vip分账
        (new CommonShare())->vipBillOrder();

        echo 33 . PHP_EOL;
        Reword::getOrder();//预处理分账

        echo 44 . PHP_EOL;

        Reword::batchSend();//批量发放分账
        echo 55 . PHP_EOL;
        Reword::batchCheck();//批量检测分账

        echo 66 . PHP_EOL;
        Reword::checkFenStatus();//检测分账状态，是否分账成功
        echo 77 . PHP_EOL;
        Reword::checkMoney(); //检测 充值订单剩下的余额
        echo 88 . PHP_EOL;
        //删除没有订单的收益和分账
        (new CommonShare())->delOrderBill();
        echo 99 . PHP_EOL;
        //同步给中台数据
        (new CommonShare())->reUserDate();
        echo 00 . PHP_EOL;
    }

    protected function update_withdraw(Input $input, Output $output)
    {
        // 查询提现结果
        $output->writeln('update_withdraw Crontab job start...' . date('Y-m-d H:i:s'));
        /*** 这里写计划任务列表集 START ***/
        (new \app\admin\model\UserWithdraw)->timer();
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('update_withdraw Crontab job end...' . date('Y-m-d H:i:s'));
    }

    protected function user_recharge(Input $input, Output $output)
    {
        // 更新余额
        $output->writeln('updateRecharge Crontab job start...' . date('Y-m-d H:i:s'));
        /*** 这里写计划任务列表集 START ***/

        (new \app\api\controller\Pay)->updateRecharge();

        /*** 这里写计划任务列表集 END ***/
        $output->writeln('updateRecharge Crontab job end...' . date('Y-m-d H:i:s'));
    }

    protected function update_amount(Input $input, Output $output)
    {
        //统计支付
        $cacheKey = 'paydaytongji123';
        $todate = date('Y-m-d');
        if (\think\Cache::get($cacheKey) != $todate) {
            //当天统计昨天的
            $todateStart = strtotime($todate) - 86400;
            $todateEnd = $todateStart + 86399;
            $sql = \addons\shopro\model\Order::where('createtime', '>=', $todateStart)
                ->where('createtime', '<=', $todateEnd)
                ->where('xw_code', '<>', '')
                ->where('status', 'in', [\addons\shopro\model\Order::STATUS_PAYED, \addons\shopro\model\Order::STATUS_FINISH])
                ->group('xw_code,city,province')
                ->field("xw_code,province,city,'{$todate}' AS `day`,SUM(pay_fee) total_pay")
                ->buildSql();
            $time = time();
            $sql = \app\admin\model\pay\Merchant::alias('m')->field("m.id mer_id,m.name,ototal.xw_code,ototal.province,ototal.city,ototal.day,ototal.total_pay,{$time} `createtime`, {$time} `updatetime`")->join([$sql => 'ototal'], 'ototal.xw_code = m.code')->fetchSql(true)->select();

            $table = \app\admin\model\pay\MerchantDay::getTable();
            $sql = "INSERT INTO `{$table}` (`mer_id`, `name`,`code`, `province`, `city`,`day`, `total_money`, `createtime`, `updatetime`) {$sql} ON DUPLICATE KEY UPDATE `total_money`=VALUES(`total_money`),`updatetime`=VALUES(`updatetime`)";
            \think\Db::execute($sql);
            \think\Cache::set($cacheKey, $todate);
        }
    }

    // 获取昨天实际支付订单
    private function ShareRetreat(Input $input, Output $output)
    {

        // 订单自动退款
        $output->writeln('订单自动退款 job start...');
        $this->autoRefund();

        // 订单自动退权益
        $output->writeln('订单自动退权益 job start...');
        $orders = (new Order())->where(['share_retreat' => 1])->limit(3)->select();

        foreach ($orders as $key => $value) {
            \db("shopro_order")->where('id', $value->id)->update(['share_retreat' => 3]);
        }

        foreach ($orders as $key => $value) {
            (new CommonShare())->Chargeback($value->id, $value->user_id, $value->order_sn);
        }
    }

    /**
     * 订单自动退款
     */
    public function autoRefund()
    {
        $aftersaleData = (new \app\admin\model\shopro\order\Aftersale)
            ->withTrashed()
            ->canOper()
            ->where('refund_status', '=', '0')
            ->limit(3)
            ->select();
        foreach ($aftersaleData as $aftersale) {
            $aftersale->refund_status = 3;     // 退款中
            $aftersale->save();
        }

        foreach ($aftersaleData as $aftersale) {
            //存在测试号 需要判断用户是否存在
            $user = \db("share_user")->where('user_id', $aftersale->user_id)->find();
            if (!$user) continue;

            $log = '退款订单号：' . $aftersale->aftersale_sn;

            $refund_money = round($aftersale->refund_fee, 2);
            if ($refund_money < 0) {
                \think\Log::write($log . '退款金额不能小于 0', 'autoRefund');
                \db("log_error")->insert([
                    'content' => $log . '退款金额不能小于 0', 'autoRefund',
                    'addtime' => time(),
                ]);
                continue;
            }
            $order = \app\admin\model\shopro\order\Order::withTrashed()->with('item')
                ->where('id', $aftersale->order_id)->find();
            if (!$order) {
                \think\Log::write($log . '订单不存在', 'autoRefund');
                \db("log_error")->insert([
                    'content' => $log . '订单不存在', 'autoRefund',
                    'addtime' => time(),
                ]);
                continue;
            }

            $items = $order->item;
            $items = array_column($items, null, 'id');
            // 当前订单已退款总金额
            $refunded_money = array_sum(array_column($items, 'refund_fee'));
            $refunded_money = 0;
            // 剩余可退款金额
            $refund_surplus_money = $order->pay_fee - $refunded_money;
            // 如果退款金额大于订单支付总金额
            if ($refund_money > $refund_surplus_money) {
                // echo '3';
                \think\Log::write($log . '退款总金额不能大于实际支付金额', 'autoRefund');
                continue;
                // $this->error('退款总金额不能大于实际支付金额');
            }

            $orderItem = $items[$aftersale['order_item_id']];

            if (!$orderItem || in_array($orderItem['refund_status'], [
                    \app\admin\model\shopro\order\OrderItem::REFUND_STATUS_OK,
                    \app\admin\model\shopro\order\OrderItem::REFUND_STATUS_FINISH,
                ])) {
                // echo '4';
                \think\Log::write($log . '订单商品已退款，不能重复退款', 'autoRefund');
                continue;
                // $this->error('订单商品已退款，不能重复退款');
            }

            \think\Db::transaction(function () use ($aftersale, $order, $orderItem, $refund_money, $refund_surplus_money) {
                $data = ['aftersale' => $aftersale, 'order' => $order, 'item' => $orderItem];
                \think\Hook::listen('aftersale_finish_before', $data);

                $aftersale->aftersale_status = \app\admin\model\shopro\order\Aftersale::AFTERSALE_STATUS_OK;    // 售后同意
                $aftersale->refund_status = \app\admin\model\shopro\order\Aftersale::REFUND_STATUS_FINISH;    // 售后同意退款
                $aftersale->refund_fee = $refund_money;     // 退款金额
                $aftersale->save();

                // 增加售后单变动记录
                \addons\shopro\model\OrderAftersaleLog::operAdd($order, $aftersale, 0, 'system', [
                    'reason' => '卖家同意退款',
                    'content' => '售后订单已退款',
                    'images' => []
                ]);

                $orderItem->aftersale_status = \app\admin\model\shopro\order\OrderItem::AFTERSALE_STATUS_OK;
                $orderItem->save();
                \addons\shopro\model\OrderAction::operAdd($order, $orderItem, 0, 'system', '系统自动同意售后退款');

                // 退款
                \app\admin\model\shopro\order\Order::startRefund($order, $orderItem, $refund_money, 0, '管理员同意售后退款');
                $data = ['aftersale' => $aftersale, 'order' => $order, 'item' => $orderItem];
                \think\Hook::listen('aftersale_finish_after', $data);
            });
        }
    }

    // 扫码推广用户 用户10分钟内不下单，自动删除关系（删除该用户）注册时间
    private function Canceluser(Input $input, Output $output)
    {
        $output->writeln(' 用户10分钟内不下单，自动删除关系 job start...');
        $t = 600;
        $del_user_time = Db::name("config")->where(['name' => 'del_user_time'])->find();//时间
        if($del_user_time && $del_user_time['value'] > 0){
            $t = $del_user_time['value'];
        }
        // 查找所有没下单用户
        $time = time() - $t;
        $ShareUser = Db::name("share_user s")->field("s.*")->where('s.addtime', '<=', $time)
            ->join("user u","u.id = s.user_id")
            ->where('s.user_id', '>', 1)
            ->where(['s.role' => 0,'u.user_type'=>0])
            ->where('s.mutual_money < 0.01')
            ->where('s.price < 0.01')
            ->where('s.parent_id > 0')
            ->where('s.score < 0.01')->select();
        foreach ($ShareUser as $key => &$value) {
            echo $key . PHP_EOL;
            //(new ShareUser())->where(['id' => $value['shareuserid']])->update(['parent_id'=>0,'inviter_id'=>0,"role_url"=>'']);
            //(new User())->where(['id' => $value['user_id']])->update(['pid'=>0]);
            $parent_id = $value['parent_id'];
            $temp_data = (new ShareUser())->where(['parent_id' => $parent_id])->select();
            foreach ($temp_data as $key => $value) {
                $role_type = $key + 1;
                (new ShareUser())->where(['id' => $value['id']])->update(['role_type' => $role_type]);
            }
        }
        echo date("Y-m-d H:i:s") . " 成功 \r\n";
        /*$output->writeln(' 用户10分钟内不下单，自动删除关系 job start...');
        $t = 600;
        $del_user_time = Db::name("config")->where(['name' => 'del_user_time'])->find();//时间
        if($del_user_time && $del_user_time['value'] > 0){
            $t = $del_user_time['value'];
        }
        // 查找所有没下单用户
        $time = time() - $t;
        $ShareUser = (new ShareUser())->where('addtime', '<=', $time)
            ->where('user_id', '>', 1)
            ->where(['role' => 0])
            ->where('mutual_money < 0.01')
            ->where('price < 0.01')
            ->where('score < 0.01')->select();
        foreach ($ShareUser as $key => &$value) {
            echo $key . PHP_EOL;
            $parent_id = $value['parent_id'];
            $temp_lists = (new ShareUser())->where(['parent_id' => $value['user_id']])->select();
            $exchange_code = (new Code())->where(['user_id' => $value['user_id']])->select();
            if (empty($temp_lists) && empty($value['is_order']) && empty($exchange_code)
            ) {
                $user_id = $value['user_id'];
                $users = \addons\shopro\model\User::get($value['user_id']);
                if (!empty($users)) {
                    $users['uid'] = $users['id'];
                    unset($users['id']);
                    $exist = Db::name("user_delete")->where('mobile', $users['mobile'])->find();
                    if (!$exist) Db::name("user_delete")->strict(false)->insert($users->toArray());
                }
                $share_user = $value;
                if (!empty($share_user)) {
                    $share_user['shareuserid'] = $share_user['id'];
                    unset($share_user['id']);
                    Db::name("share_user_delete")->strict(false)->insert($share_user->toArray());
                }
                $before_mobile = $users['mobile'];
                Auth::instance()->delete($value['user_id']);
                (new ShareUser())->where(['id' => $value['shareuserid']])->delete();
                //删除好友关系
                (new CommonShare())->delUserf($value['user_id']);
                UserChangeLog::create(['user_id' => $user_id, 'before_mobile' => $before_mobile, 'after_mobile' => 0, 'memo' => '直接删除用户']);
            }

            $temp_data = (new ShareUser())->where(['parent_id' => $parent_id])->select();
            foreach ($temp_data as $key => $value) {
                $role_type = $key + 1;
                (new ShareUser())->where(['id' => $value['id']])->update(['role_type' => $role_type]);
            }
        }
        echo date("Y-m-d H:i:s") . " 成功 \r\n";*/
    }
}
